package controllers

import (
	"encoding/json"
	//	"errors"
	"gitee.com/lzqysoft/ims/models"
	"strconv"
	//	"strings"
	"gitee.com/lzqysoft/ims/libs/encrypt"

	"github.com/astaxie/beego"
	//	"sys/common/log"
	"time"
)

// BulletinController 公告
type BulletinController struct {
	CommonController
}

// URLMapping 方法映射
func (c *BulletinController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetVaildateBulletins", c.GetVaildateBulletins)
}

// Post 插入
// @Title Post
// @Description create Bulletin
// @Param	body		body 	models.Bulletin	true		"body for Bulletin content"
// @Success 201 {int} models.Bulletin
// @Failure 403 body is empty
// @router / [post]
func (c *BulletinController) Post() {
	var v models.Bulletin
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &v)
	beego.Debug(v.Btime)
	tdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := tdata.(map[string]interface{})
	// v.Title = sdata["Title"].(string)
	// v.Content = sdata["Content"].(string)
	// //	org, err := models.GetOrganizationById(user.Organization.Id)
	// if err != nil {
	// 	c.RetError(ErrNoUser)
	// }
	// v.OrgName = user.Organization.Name

	// v.Type, _ = strconv.Atoi(sdata["Type"].(string))

	btime := sdata["Btime"].(string)
	etime := sdata["Etime"].(string)

	tm1, _ := time.Parse("2006-01-02", btime)
	tm2, _ := time.Parse("2006-01-02", etime)

	v.Btime = tm1
	v.Etime = tm2

	v.Ctime = time.Now()

	v.Organization = user.Organization
	v.Dept = user.Dept[0]
	v.Creater = user.Name
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Id = encrypt.GetGuid()
	//	log.Info("user is :", user)
	//	userprof, _ := models.GetUserprofById(user.Id)
	//	log.Info("userprof is :", userprof)
	beego.Debug(v.Btime)
	beego.Debug(v.Dept)
	_, err = models.AddBulletin(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)

	}
	c.Dlog("添加了公告,id 是", v.Id)
	c.RetSuccess(v.Id)

}

// GetOne get Bulletin by id
// @Title Get
// @Description get Bulletin by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Bulletin
// @Failure 403 :id is empty
// @router /:id [get]
func (c *BulletinController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetBulletinById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll get Bulletin
// @Title Get All
// @Description get Bulletin
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Bulletin
// @Failure 403
// @router /GetAll [post]
func (c *BulletinController) GetAll() {
	user := c.User
	var ob map[string]interface{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &ob)
	beego.Debug(ob)
	beego.Debug(c.GetString("tdata"))
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrInputData)
	}
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]interface{})
	var limit int64 = -1
	var offset int64
	sdata, _ := rdata.(map[string]interface{})
	//	role, err := models.GetRoleByUserId(user.Id)
	if err != nil {
		c.RetError(ErrPermission)
	}
	query["Isdelete"] = "0"
	//用户角色不是系统管理员的筛选单位
	//	if role.Id > 2 {
	switch user.Role[0].Type {
	case 1:
		query["Organization__Id"] = user.Organization.Id
	case 2:
		ids := models.GetDeptChildrenStr(user.Dept[0].Id)
		query["Dept__Id__in"] = *ids
	}
	//	query["Organization__ID"] = strconv.FormatInt(user.Organization.Id, 10)
	//	}
	ipage, _ := sdata["page"].(string)
	page, _ := strconv.ParseInt(ipage, 10, 64)
	ipagesize, _ := sdata["pagesize"].(string)
	pagesize, _ := strconv.ParseInt(ipagesize, 10, 64)
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * pagesize
	}
	limit = pagesize
	l, count, err := models.GetAllBulletin(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.RetError(ErrNoData)
	}
	tabledata := make(map[string]interface{})
	tabledata["total"] = count
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// Update update the Bulletin
// @Title Update
// @Description update the Bulletin
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Bulletin	true		"body for Bulletin content"
// @Success 200 {object} models.Bulletin
// @Failure 403 :id is not int
// @router /Update [post]
func (c *BulletinController) Update() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, _ := strconv.ParseInt(sid, 10, 64)
	v, err := models.GetBulletinById(id)
	if err != nil {
		c.RetError(ErrInputData)
	}
	u := v
	v.Title = sdata["Title"].(string)
	v.Content = sdata["Content"].(string)
	//	beego.Debug("v.Content:", v.Content)
	//	beego.Debug("sdata[]：", sdata["Content"])
	btime := sdata["Btime"].(string)
	etime := sdata["Etime"].(string)

	tm1, _ := time.Parse("2006-01-02", btime)
	tm2, _ := time.Parse("2006-01-02", etime)

	v.Btime = tm1
	v.Etime = tm2
	v.Updater = user.Name
	v.Utime = time.Now()
	err = models.UpdateBulletinById(v)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)

	}
	c.Dlog("修改了公告", id, 1, u)
	c.RetSuccess(id)
}

// Delete delete the Bulletin
// @Title Delete
// @Description delete the Bulletin
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *BulletinController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError(ErrInputData)
	}
	if err := models.SoftDeleteBulletin(id, user.Name); err != nil {
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(id)
}

// DeleteBulletins Delete 多个Bulletins
// @Title DeleteBulletins
// @Description DeleteBulletins
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /DeleteBulletins [post]
func (c *BulletinController) DeleteBulletins() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteBulletin(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了角色", id)
	}
	c.RetSuccess("ok")
}

// GetVaildateBulletins 获取有效的公告
// @Title GetVaildateBulletins
// @Description 根据单位获取有效的公告
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /GetVaildateBulletins [get]
func (c *BulletinController) GetVaildateBulletins() {
	user := c.User
	//	orgId, _ := c.GetInt64("OrgId")
	//	orgId := c.GetSession("org").(models.Organization).Id
	bs := models.GetBulletinsByUser(*user)
	c.RetSuccess(bs)

}
